package com.sjzd.server.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 *  验证码controller
 * @author ZFQ
 * @date 2021/2/24
 */
@Api(tags = "验证码controller")
@RestController
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @ApiOperation(value = "获取验证码",produces = "image/jpeg")
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest req, HttpServletResponse resp) {
        //定义response输出类型为image/jpeg
        resp.setDateHeader("Expires",0);
        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
        resp.setHeader("Pragma", "no-cache");
        resp.setContentType("image/jpeg");
        // -------生成验证码----
        // 生成验证码文本
        String verifyCode = defaultKaptcha.createText();
        // 将验证码放入session用于后期比对
        req.getSession().setAttribute("verifyCode", verifyCode);
        // 将验证码放入图片中
        BufferedImage image = defaultKaptcha.createImage(verifyCode);
        ServletOutputStream out = null;
        try {
           out = resp.getOutputStream();
           ImageIO.write(image, "jpg", out);
           out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
